July, 1994 - Vol. 1 No. 7


Listing A: ITERATOR.CPP

#include <iostream.h>

//******** intArray class ********

class intArray
{
  friend class forwardIterator;
  friend class reverseIterator;

    int* data;
    int max;

  public:
    intArray(int siz�e){
      max = size;
      data = new int[max]; }

    ~intArray(){
      delete data; }

    int&
    operator[](const int index){
      return data[index]; }
};


//******** forwardIterator class ********

class forwardIterator
{
  protected:
    int currentIndex;   // the current index
    int end;           // last valid index
    int beg;           // first valid index
    intArray& myArray; // companion container

  private:
    virtual            // Return the current
    int                // index and increment it.
    advanceIndex(){
      return currentIndex++; }

  public:
    // constructor
    forwardIterator(intArray& array) :
     myArray(array){
      end = myArray.max - 1;
      beg = 0;
      currentIndex = 0; }

    // conversion to integer constructor
    operator int () {
      if(currentIndex <= end)
        return 1;
      reset();
      return 0; }

    virtual
    void
    reset(){
      currentIndex = beg; }

    virtual            // Return a reference to
    int&               // the current item and
    operator () (){    // move to the next item.
      return myArray[advanceIndex()]; }
};


//******** reverseIterator class ********

class reverseIterator :
  public forwardIterator
{
  private:
    virtual            // Return the current
    int                // index and decrement it.
    advanceIndex(){
      return currentIndex--; }

  public:
    // constructor
    reverseIterator(intArray& array) :
     forwardIterator(array){
      end = 0;
      beg = myArray.max - 1;
      currentIndex = beg; }

    // conversion to integer constructor
    operator int () {
      if(currentIndex >= end)
        return 1;
      reset();
      return 0; }
};


//******** beginning of main() ********

int 
main(){
  intArray IntArray(10);
  forwardIterator FwdIterator(IntArray);
  reverseIterator RevIterator(IntArray);

  int value = 0;

  while(FwdIterator)
    FwdIterator() = (value++) * 2;

  FwdIterator.reset();

  while(FwdIterator && RevIterator){
    cout << FwdIterator() << "  ";
    cout << RevIterator() << endl; }

  return 0;
}


Return to "C++ Programming - An introduction to iterator classes"


Copyright (c) 1996 The Cobb Group, a division of Ziff-Davis Publishing Company. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of Ziff-Davis Publishing Company is prohibited. The Cobb Group and The Cobb Group logo are trademarks of Ziff-Davis Publishing Company.